<template>
    <div class="head">
        <van-nav-bar   title="地址管理"  left-arrow @click-left="$router.back()"> 
            <template #right>
                <van-icon name="ellipsis" size="18" />
            </template>
         </van-nav-bar>
    </div>
    <main>
        <van-address-list
        v-model="cartList.chosenAddressId"
        :list="cartList.list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @click-item="goToOrder"
        />
    </main>
</template>
<script  setup>
import { onMounted ,reactive,ref} from 'vue';
import { addressList } from "../../api/index.js"
import { useRouter,useRoute} from 'vue-router';
import { showConfirmDialog } from 'vant';
let router =useRouter()
let edit =true
let cartList =reactive({
    list:[],
    chosenAddressId:''
})
onMounted(()=>{
    // 添加地址
    addressList().then(res=>{
        cartList.list=res.data.map(item=>{
            return{
                id:item.addressId,
                name:item.userName,
                tel:item.userPhone,
                address:item.provinceName+item.cityName+
                item.regionName+item.detailAddress,
                isDefault:item.defaultFlag
            }
        })
    })
 
})
let onAdd=()=>{
    edit=false
    router.push('/addresaddedit')
}
// 进入编辑地址页面
let onEdit=(item)=>{
    edit=false
    console.log(item.id);
    router.push('/addresaddedit?addressId='+item.id)
}
// 进入订单页
let goToOrder=(item)=>{
    console.log(item);
    if(!edit){
        edit=true
        return
    }
    showConfirmDialog({
    message:'是否使用该地址',
    })
    .then(() => {
        // on confirm
        router.push({
            path:"/order",
            query:{addressId:item.id}
        })
    })
    .catch(() => {
        // on cancel
    });
}
</script>
<style lang="less">
.head{
    width: 100%;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 10;
}
main{
    margin-top: 50px;
}
</style>